<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>性能问题诊断工具</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f5f5f5;
            line-height: 1.6;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 700;
        }
        .header p {
            margin: 10px 0 0;
            opacity: 0.9;
        }
        .content {
            padding: 30px;
        }
        .section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            background: #f9fafb;
        }
        .section h2 {
            color: #1f2937;
            margin-top: 0;
            font-size: 20px;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        .diagnostic-item {
            background: white;
            padding: 15px;
            margin: 10px 0;
            border-radius: 6px;
            border-left: 4px solid #667eea;
        }
        .diagnostic-item.warning {
            border-left-color: #f59e0b;
            background: #fffbeb;
        }
        .diagnostic-item.error {
            border-left-color: #ef4444;
            background: #fef2f2;
        }
        .diagnostic-item.success {
            border-left-color: #10b981;
            background: #f0fdf4;
        }
        .btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            margin: 5px;
            transition: background 0.3s;
        }
        .btn:hover {
            background: #5a67d8;
        }
        .btn.danger {
            background: #ef4444;
        }
        .btn.danger:hover {
            background: #dc2626;
        }
        .btn.success {
            background: #10b981;
        }
        .btn.success:hover {
            background: #059669;
        }
        .code {
            background: #1f2937;
            color: #f9fafb;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            overflow-x: auto;
            margin: 10px 0;
        }
        .status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            margin-left: 10px;
        }
        .status.good {
            background: #d1fae5;
            color: #065f46;
        }
        .status.warning {
            background: #fef3c7;
            color: #92400e;
        }
        .status.bad {
            background: #fee2e2;
            color: #991b1b;
        }
        .log-container {
            background: #1f2937;
            color: #f9fafb;
            padding: 15px;
            border-radius: 6px;
            max-height: 300px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .log-item {
            margin: 2px 0;
            padding: 2px 0;
        }
        .log-item.info {
            color: #60a5fa;
        }
        .log-item.warning {
            color: #fbbf24;
        }
        .log-item.error {
            color: #f87171;
        }
        .log-item.success {
            color: #34d399;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔧 性能问题诊断工具</h1>
            <p>专门解决 detectPageLang 等外部脚本性能问题</p>
        </div>

        <div class="content">
            <!-- 问题诊断 -->
            <div class="section">
                <h2>🔍 问题诊断</h2>
                <div id="diagnostic-results">
                    <div class="diagnostic-item">
                        <strong>正在检测性能问题...</strong>
                        <span class="status warning">检测中</span>
                    </div>
                </div>
                <button class="btn" onclick="runDiagnostics()">重新检测</button>
                <button class="btn danger" onclick="clearDiagnostics()">清除结果</button>
            </div>

            <!-- 解决方案 -->
            <div class="section">
                <h2>💡 解决方案</h2>
                <div class="diagnostic-item">
                    <h3>1. 禁用浏览器扩展</h3>
                    <p>detectPageLang 通常来自翻译扩展或语言检测扩展</p>
                    <button class="btn" onclick="openExtensionsPage()">打开扩展管理</button>
                </div>
                <div class="diagnostic-item">
                    <h3>2. 使用无痕模式测试</h3>
                    <p>在无痕模式下测试网站性能，排除扩展影响</p>
                    <button class="btn" onclick="openIncognito()">打开无痕窗口</button>
                </div>
                <div class="diagnostic-item">
                    <h3>3. 清理浏览器缓存</h3>
                    <p>清理浏览器缓存和Cookie，重置浏览器状态</p>
                    <button class="btn" onclick="openClearData()">清理数据</button>
                </div>
                <div class="diagnostic-item">
                    <h3>4. 检查网络连接</h3>
                    <p>确保网络连接稳定，避免网络延迟影响</p>
                    <button class="btn" onclick="testNetworkSpeed()">测试网速</button>
                </div>
            </div>

            <!-- 性能监控 -->
            <div class="section">
                <h2>📊 实时性能监控</h2>
                <div class="diagnostic-item">
                    <strong>FPS:</strong> <span id="fps-display">-</span>
                    <span class="status" id="fps-status">检测中</span>
                </div>
                <div class="diagnostic-item">
                    <strong>内存使用:</strong> <span id="memory-display">-</span>
                    <span class="status" id="memory-status">检测中</span>
                </div>
                <div class="diagnostic-item">
                    <strong>页面加载时间:</strong> <span id="loadtime-display">-</span>
                    <span class="status" id="loadtime-status">检测中</span>
                </div>
                <button class="btn" onclick="startMonitoring()">开始监控</button>
                <button class="btn danger" onclick="stopMonitoring()">停止监控</button>
            </div>

            <!-- 日志输出 -->
            <div class="section">
                <h2>📝 诊断日志</h2>
                <div id="log-container" class="log-container">
                    <div class="log-item info">[INFO] 性能诊断工具已启动</div>
                </div>
                <button class="btn" onclick="clearLogs()">清除日志</button>
                <button class="btn success" onclick="exportLogs()">导出日志</button>
            </div>

            <!-- 快速修复 -->
            <div class="section">
                <h2>⚡ 快速修复</h2>
                <div class="diagnostic-item">
                    <h3>自动优化脚本</h3>
                    <p>运行自动优化脚本来提升页面性能</p>
                    <button class="btn success" onclick="runAutoOptimization()">运行优化</button>
                </div>
                <div class="code" id="optimization-code">
// 自动优化脚本将在这里显示
                </div>
            </div>
        </div>
    </div>

    <script>
        let monitoringInterval = null;
        let frameCount = 0;
        let lastTime = performance.now();

        // 运行诊断
        function runDiagnostics() {
            addLog('info', '开始运行性能诊断...');
            
            const results = document.getElementById('diagnostic-results');
            results.innerHTML = '';

            // 检测外部脚本
            const scripts = Array.from(document.scripts);
            const externalScripts = scripts.filter(script => {
                return script.src && !script.src.includes(window.location.origin);
            });

            if (externalScripts.length > 0) {
                const item = createDiagnosticItem(
                    `检测到 ${externalScripts.length} 个外部脚本`,
                    'warning',
                    '这可能是性能问题的原因'
                );
                results.appendChild(item);
                addLog('warning', `发现 ${externalScripts.length} 个外部脚本`);
            }

            // 检测 detectPageLang 函数
            if (typeof window.detectPageLang === 'function') {
                const item = createDiagnosticItem(
                    '检测到 detectPageLang 函数',
                    'error',
                    '这通常来自浏览器扩展，会严重影响性能'
                );
                results.appendChild(item);
                addLog('error', '检测到 detectPageLang 函数');
            }

            // 检测性能问题
            const navigation = performance.getEntriesByType('navigation')[0];
            if (navigation) {
                const loadTime = navigation.loadEventEnd - navigation.fetchStart;
                const status = loadTime > 3000 ? 'error' : loadTime > 1000 ? 'warning' : 'success';
                const item = createDiagnosticItem(
                    `页面加载时间: ${Math.round(loadTime)}ms`,
                    status,
                    status === 'success' ? '加载速度正常' : '加载时间过长'
                );
                results.appendChild(item);
                addLog(status === 'success' ? 'info' : 'warning', `页面加载时间: ${Math.round(loadTime)}ms`);
            }

            // 检测内存使用
            if (performance.memory) {
                const usedMB = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024);
                const status = usedMB > 100 ? 'error' : usedMB > 50 ? 'warning' : 'success';
                const item = createDiagnosticItem(
                    `内存使用: ${usedMB}MB`,
                    status,
                    status === 'success' ? '内存使用正常' : '内存使用过高'
                );
                results.appendChild(item);
                addLog(status === 'success' ? 'info' : 'warning', `内存使用: ${usedMB}MB`);
            }

            addLog('success', '性能诊断完成');
        }

        // 创建诊断项
        function createDiagnosticItem(title, type, description) {
            const item = document.createElement('div');
            item.className = `diagnostic-item ${type}`;
            item.innerHTML = `
                <strong>${title}</strong>
                <span class="status ${type}">${type.toUpperCase()}</span>
                <p style="margin: 5px 0 0; font-size: 14px; color: #6b7280;">${description}</p>
            `;
            return item;
        }

        // 清除诊断结果
        function clearDiagnostics() {
            document.getElementById('diagnostic-results').innerHTML = `
                <div class="diagnostic-item">
                    <strong>诊断结果已清除</strong>
                    <span class="status warning">等待检测</span>
                </div>
            `;
            addLog('info', '诊断结果已清除');
        }

        // 开始监控
        function startMonitoring() {
            if (monitoringInterval) return;

            addLog('info', '开始性能监控');
            monitoringInterval = setInterval(() => {
                updateFPS();
                updateMemory();
                updateLoadTime();
            }, 1000);
        }

        // 停止监控
        function stopMonitoring() {
            if (monitoringInterval) {
                clearInterval(monitoringInterval);
                monitoringInterval = null;
                addLog('info', '停止性能监控');
            }
        }

        // 更新FPS
        function updateFPS() {
            const now = performance.now();
            const delta = now - lastTime;
            frameCount++;

            if (delta >= 1000) {
                const fps = Math.round((frameCount * 1000) / delta);
                document.getElementById('fps-display').textContent = fps;
                
                const status = fps > 50 ? 'good' : fps > 30 ? 'warning' : 'bad';
                document.getElementById('fps-status').textContent = status.toUpperCase();
                document.getElementById('fps-status').className = `status ${status}`;
                
                frameCount = 0;
                lastTime = now;
            }
        }

        // 更新内存
        function updateMemory() {
            if (performance.memory) {
                const usedMB = Math.round(performance.memory.usedJSHeapSize / 1024 / 1024);
                document.getElementById('memory-display').textContent = `${usedMB}MB`;
                
                const status = usedMB > 100 ? 'bad' : usedMB > 50 ? 'warning' : 'good';
                document.getElementById('memory-status').textContent = status.toUpperCase();
                document.getElementById('memory-status').className = `status ${status}`;
            }
        }

        // 更新加载时间
        function updateLoadTime() {
            const navigation = performance.getEntriesByType('navigation')[0];
            if (navigation) {
                const loadTime = Math.round(navigation.loadEventEnd - navigation.fetchStart);
                document.getElementById('loadtime-display').textContent = `${loadTime}ms`;
                
                const status = loadTime > 3000 ? 'bad' : loadTime > 1000 ? 'warning' : 'good';
                document.getElementById('loadtime-status').textContent = status.toUpperCase();
                document.getElementById('loadtime-status').className = `status ${status}`;
            }
        }

        // 添加日志
        function addLog(level, message) {
            const container = document.getElementById('log-container');
            const logItem = document.createElement('div');
            logItem.className = `log-item ${level}`;
            logItem.textContent = `[${new Date().toLocaleTimeString()}] [${level.toUpperCase()}] ${message}`;
            container.appendChild(logItem);
            container.scrollTop = container.scrollHeight;
        }

        // 清除日志
        function clearLogs() {
            document.getElementById('log-container').innerHTML = '';
            addLog('info', '日志已清除');
        }

        // 导出日志
        function exportLogs() {
            const logs = document.getElementById('log-container').textContent;
            const blob = new Blob([logs], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `performance-logs-${Date.now()}.txt`;
            a.click();
            URL.revokeObjectURL(url);
            addLog('success', '日志已导出');
        }

        // 打开扩展管理页面
        function openExtensionsPage() {
            addLog('info', '尝试打开扩展管理页面');
            // 不同浏览器的扩展管理页面
            const urls = [
                'chrome://extensions/',
                'edge://extensions/',
                'about:addons'
            ];
            
            // 尝试打开第一个URL
            try {
                window.open(urls[0], '_blank');
                addLog('success', '已打开扩展管理页面');
            } catch (e) {
                addLog('error', '无法自动打开扩展管理页面，请手动访问');
            }
        }

        // 打开无痕窗口
        function openIncognito() {
            addLog('info', '建议使用无痕模式测试');
            addLog('info', 'Chrome: Ctrl+Shift+N');
            addLog('info', 'Firefox: Ctrl+Shift+P');
            addLog('info', 'Edge: Ctrl+Shift+N');
        }

        // 打开清理数据页面
        function openClearData() {
            addLog('info', '建议手动清理浏览器数据');
            addLog('info', 'Chrome: 设置 > 隐私和安全 > 清除浏览数据');
            addLog('info', 'Firefox: 设置 > 隐私与安全 > 清除数据');
            addLog('info', 'Edge: 设置 > 隐私、搜索和服务 > 清除浏览数据');
        }

        // 测试网速
        function testNetworkSpeed() {
            addLog('info', '开始测试网络速度...');
            const startTime = performance.now();
            
            fetch('/api/test', { cache: 'no-cache' })
                .then(response => {
                    const endTime = performance.now();
                    const duration = endTime - startTime;
                    addLog('success', `网络响应时间: ${Math.round(duration)}ms`);
                })
                .catch(error => {
                    addLog('error', '网络测试失败: ' + error.message);
                });
        }

        // 运行自动优化
        function runAutoOptimization() {
            addLog('info', '开始运行自动优化...');
            
            const optimizationCode = `
// 自动优化脚本
console.log('🚀 开始自动优化...');

// 1. 禁用不必要的动画
document.documentElement.style.setProperty('--animation-duration', '0s');

// 2. 优化图片加载
const images = document.querySelectorAll('img');
images.forEach(img => {
    if (!img.loading) {
        img.loading = 'lazy';
    }
});

// 3. 预加载关键资源
const preloadLink = document.createElement('link');
preloadLink.rel = 'preload';
preloadLink.href = '/api/videos';
preloadLink.as = 'fetch';
document.head.appendChild(preloadLink);

// 4. 优化DOM查询
const originalQuerySelector = document.querySelector;
document.querySelector = function(selector) {
    const start = performance.now();
    const result = originalQuerySelector.call(this, selector);
    const duration = performance.now() - start;
    if (duration > 10) {
        console.warn('慢查询:', selector, duration + 'ms');
    }
    return result;
};

console.log('✅ 自动优化完成');
            `;

            document.getElementById('optimization-code').textContent = optimizationCode;
            
            try {
                eval(optimizationCode);
                addLog('success', '自动优化脚本执行成功');
            } catch (error) {
                addLog('error', '自动优化脚本执行失败: ' + error.message);
            }
        }

        // 页面加载完成后自动运行诊断
        window.addEventListener('load', () => {
            setTimeout(() => {
                runDiagnostics();
                startMonitoring();
            }, 1000);
        });
    </script>
</body>
</html>
